package com.dwxt.community.service;

import com.dwxt.common.base.*;
import com.dwxt.common.util.*;
import com.dwxt.community.dao.*;
import com.dwxt.community.entity.*;
import com.dwxt.community.entity.enumerate.*;
import com.dwxt.community.entity.vo.*;
import com.github.pagehelper.*;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.transaction.annotation.*;

import java.util.*;
import java.util.stream.*;

@Service
public class InformationService {

    @Autowired
    private InformationMapper informationMapper;
    @Autowired
    private AdLocationMapper adLocationMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private IntegralService integralService;
    @Autowired
    private UserActionRecordService userActionRecordService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private InformationStarUserMapper informationStarUserMapper;
    @Value("${information.recommend.max}")
    private Integer informationMax;
    @Value("${information.recommend.min}")
    private Integer informationMin;

    private Logger log = LoggerFactory.getLogger(InformationService.class);


    /**
     * 资讯列表 or 搜索 后台
     */
    public BaseResult get(Integer pageNum, Integer pageSize, String type, String name, Integer release, boolean notAdLocation, Integer recommend) {
        PageHelper.startPage(pageNum, pageSize);
        List<InformationVo> informations = informationMapper.selectAll(type, name, release, notAdLocation, recommend);
        return BaseResult.ok(new PageInfo<>(informations));
    }

    /**
     * 资讯列表 or 搜索  前台
     */
    public BaseResult get(Integer pageNum, Integer pageSize, String type, Integer recommend) {
        if (recommend != null && recommend == 1) {
            List<Information> information = informationMapper.selectByLocationType(2);
            return BaseResult.ok(new PageInfo(information));
        }

        PageHelper.startPage(pageNum, pageSize);
        //以前版本
        List<InformationVo> informations = informationMapper.selectAllDesk(type, recommend);
        //防止推荐返回内容过多
        if (recommend != null && recommend == 1 && informations.size() > informationMax) {
            informations = informations.stream().limit(informationMax).collect(Collectors.toList());
        }
        String userId = null;
        try {
            userId = PartyUtil.getCurrentUserId();
        } catch (ExpiredJwtException e) {
            return BaseResult.ok(new PageInfo<>(informations));
        }
        if (StringUtils.isNotBlank(userId)) {
            userService.updateLastLoginTime(userId);
        }
        return BaseResult.ok(new PageInfo<>(informations));
    }

    /**
     * 添加资讯
     *
     * @param information
     */
    public BaseResult insert(InformationWithBLOBs information) {
        Date currDate = new Date();
        information.setCreateTime(currDate);
        information.setUpdateTime(currDate);
        if (StateConstant.RELEASE.getCode().equals(information.getRelease())) {
            //设置发布时间
            information.setReleaseTime(currDate);
        }
        //设置ID
        information.setId(IDUtils.genItemId());
        return BaseResult.ok(informationMapper.insertSelective(information));
    }

    /**
     * 删除资讯  物理删除
     *
     * @param id
     * @return {"status":200,"msg":"SUCCESS","data":null}
     */
    @Transactional(rollbackFor = Exception.class)
    public BaseResult del(String id) {
        //删除评论表
        commentService.delByInformationId(id);
        //删除 点赞关系表
        informationStarUserMapper.deleteByInformationId(id);
        //删除资讯表
        informationMapper.deleteByPrimaryKey(id);
        //删除推荐资讯表
        AdLocationExample adE = new AdLocationExample();
        adE.createCriteria().andInformationIdEqualTo(id);
        adLocationMapper.deleteByExample(adE);
        return BaseResult.ok();
    }

    /**
     * 修改资讯
     *
     * @param information
     * @return {"status":200,"msg":"SUCCESS","data":null}
     */
    public BaseResult update(InformationWithBLOBs information) {

        Information delLocationInformation = informationMapper.selectByAdLocationId(information.getAdLocationId());
        if (delLocationInformation != null) {
            delLocation(delLocationInformation.getId());
        }
        return BaseResult.build(informationMapper.updateByPrimaryKeySelective(information) > 0 ? StatusCode.SUCCESS : StatusCode.FAIL);
    }

    /**
     * 资讯 发布 or 撤下
     *
     * @param id
     * @return {"status":200,"msg":"SUCCESS","data":null}
     */
    public BaseResult release(String id) {
        InformationWithBLOBs information = informationMapper.selectByPrimaryKey(id);
        if (information == null) {
            return BaseResult.build(StatusCode.PARAMETER_WRONG);
        }
        //判断当前资讯是否已经发布
        if (StateConstant.RELEASE.getCode().equals(information.getRelease())) {
            //设置为未发布
            information.setRelease(StateConstant.NOT_RELEASE.getCode());
            //撤下热门
            AdLocationExample adLocationExample = new AdLocationExample();
            adLocationExample.createCriteria().andInformationIdEqualTo(id);
            List<AdLocation> adLocations = adLocationMapper.selectByExample(adLocationExample);
            if (ObjectUtils.isNotEmpty(adLocations)) {
                for (AdLocation adl : adLocations) {
                    adLocationMapper.deleteByPrimaryKey(adl.getId());
                }
            }
        } else if (StateConstant.NOT_RELEASE.getCode().equals(information.getRelease())) {
            //设置为发布
            information.setRelease(StateConstant.RELEASE.getCode());
        }
        information.setReleaseTime(new Date());
        System.out.println("new Date() =>" + information.getReleaseTime());
        log.error("new Date() => {}", information.getReleaseTime());
        int i = informationMapper.updateByPrimaryKeySelective(information);
        return BaseResult.build(i > 0 ? StatusCode.SUCCESS : StatusCode.FAIL);
    }

    /**
     * 点击量 + 1
     *
     * @param id
     * @return
     */
    public synchronized BaseResult addHits(String id) {

        InformationWithBLOBs information = informationMapper.selectByPrimaryKey(id);
        if (information == null) {
            return BaseResult.build(StatusCode.PARAMETER_WRONG);
        }
        information.setHits(information.getHits() + 1);
        int i = informationMapper.updateByPrimaryKeySelective(information);
        return BaseResult.build(i > 0 ? StatusCode.SUCCESS : StatusCode.FAIL);
    }


    /**
     * 点赞 or 取消点赞
     *
     * @param informationId
     * @return
     */
    public BaseResult clickStar(String informationId) {
        String userId = PartyUtil.getCurrentUserId();
        if (StringUtils.isBlank(userId)) {
            return BaseResult.build(StatusCode.USER_NOT_EXIST);
        }
        InformationStarUser informationStarUser = informationStarUserMapper.selectByInformationStarUser(informationId, userId);
        int i;
        if (informationStarUser == null) {
            //新增
            informationStarUser = new InformationStarUser();
            informationStarUser.setUserId(userId);
            informationStarUser.setInformationId(informationId);
            i = informationStarUserMapper.insert(informationStarUser);
            //行为记录
            userActionRecordService.addActionRecord(informationId, userId, "资讯", ActionInfoEnum.star.getCode());
        } else {
            //删除
            i = informationStarUserMapper.deleteByPrimaryKey(informationStarUser.getId());
            //行为记录
            userActionRecordService.addActionRecord(informationId, userId, "资讯", ActionInfoEnum.unstar.getCode());
        }
        return BaseResult.build(i > 0 ? StatusCode.SUCCESS : StatusCode.FAIL);
    }

    /**
     * 资讯详情
     *
     * @param id
     * @return
     */
    public BaseResult detail(String id) {
        InformationVo informationVo = informationMapper.selectById(id);
        if (informationVo == null) {
            return BaseResult.build(StatusCode.INFORMATION_NOT_EXIST);
        }
        String userId = PartyUtil.getCurrentUserId();
        if (ObjectUtils.isNotEmpty(userId)) {
            informationVo.setStarIs(informationStarUserMapper.selectByInformationStarUser(id, userId) != null);
        } else {
            informationVo.setStarIs(false);
        }
        //点击数
        addHits(id);
        //添加行为记录
        userActionRecordService.addActionRecord(id, userId, "资讯", ActionInfoEnum.hit.getCode());
        return BaseResult.ok(informationVo);
    }

    /**
     * 获取资讯包含 位置信息
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public BaseResult getByLocation(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<InfomationLocationVo> infomationLocationVos = informationMapper.getByLocation();
        return BaseResult.ok(new PageInfo<>(infomationLocationVos));
    }

    /**
     * 清除资讯位置
     *
     * @param id
     * @return
     */
    public BaseResult delLocation(String id) {
        informationMapper.delLocation(id);
        return BaseResult.ok();
    }

    /**
     * 轮播图
     */
    public BaseResult selectViewPaper() {
        return BaseResult.ok(informationMapper.selectViewPaper());
    }

    public BaseResult selectAdInfo() {
        return BaseResult.ok(informationMapper.selectAdInfo());
    }

    public Integer countByCreateTime(String date) {
        return informationMapper.countByCreateTime(date);
    }

    public BaseResult getRecommend(Integer type) {
        String userId = null;
        try {
            userId = PartyUtil.getCurrentUserId();
        } catch (ExpiredJwtException e) {
            return BaseResult.ok(informationMapper.selectByLocationType(type));
        }
        if (StringUtils.isNotBlank(userId)) {
            userService.updateLastLoginTime(userId);
        }
        return BaseResult.ok(informationMapper.selectByLocationType(type));
    }
}
